import axios from 'axios';
import { getUser } from '@/utils/auth';
import qs from 'qs';

axios.defaults.headers = {
	'Content-Type': 'application/json'
};

const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API,
	timeout: 60000
});

let flatten = (arr) => { 
	return [].concat( ...arr.map(x => Array.isArray(x) ? flatten(x) : x) ) 
}

service.interceptors.request.use(
	config => {
		let user = getUser();
		let jwtToken;
		if(user) {
			jwtToken = user.jwtToken;
		}
		if(config.method) {
			config.params = config.params || {};
			if(jwtToken) {
				config.params['jwtToken'] = jwtToken;
			}
			if('GET' == config.method.toUpperCase()) {
				config.paramsSerializer = function(params) {
					return qs.stringify(params, {arrayFormat: 'repeat'})
				}
			} else if('POST' == config.method.toUpperCase()) {
				if(config.headers['Content-Type'] == 'application/x-www-form-urlencoded') {
					var formData = new FormData();
					for(var key in config.data) {
						var value = config.data[key];
						if(value instanceof Array) {
							value = flatten(value);
							for(var i = 0; i < value.length; i++) {
								formData.append(key, value[i]);
							}
						} else {
							formData.append(key, value);
						}
					}
					config.data = formData;
				} else {
					config.data = config.data || {};
					config.data = JSON.stringify(config.data);
				}
			}
		}
		return config;
	},
	() => {
		return Promise.reject({
			success: false,
			detail: {
				code: 900,
				msg: '发送请求失败'
			}
		});
	}
);

service.interceptors.response.use(
	response => {
		const data = response.data;
		if(data == null) {
			return Promise.reject({
				success: false,
				detail: {
					code: 900,
					msg: '服务器响应错误'
				}
			});
		}
		if(data.success == false) {
			return Promise.reject(data);
		}
		return data;
	},
	error => {
		if(error.response == null || error.response.data == null) {
			return Promise.reject({
				success: false,
				detail: {
					code: 900,
					msg: '服务器无响应'
				}
			});
		} else {
			return Promise.reject({
				success: false,
				detail: {
					code: 900,
					msg: error.response.data.error
				}
			});
		}
	}
);

export default service
